/*
 * SHOPTNT 版权所有。
 * 未经许可，您不得使用此文件。
 * 官方地址：www.shoptnt.cn
 */
package cn.shoptnt.consumer.shop.trade.consumer;

import cn.shoptnt.client.promotion.FullDiscountGiftClient;
import cn.shoptnt.client.trade.OrderMetaClient;
import cn.shoptnt.consumer.core.event.OrderStatusChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.shoptnt.model.base.message.OrderStatusChangeMsg;
import cn.shoptnt.model.goods.enums.QuantityType;
import cn.shoptnt.model.promotion.fulldiscount.dos.FullDiscountGiftDO;
import cn.shoptnt.model.promotion.tool.vo.GiveGiftVO;
import cn.shoptnt.model.trade.order.dos.OrderMetaDO;
import cn.shoptnt.model.trade.order.dto.OrderDTO;
import cn.shoptnt.model.trade.order.enums.OrderMetaKeyEnum;
import cn.shoptnt.model.trade.order.enums.OrderServiceStatusEnum;
import cn.shoptnt.model.trade.order.enums.OrderStatusEnum;
import cn.shoptnt.framework.util.JsonUtil;
import cn.shoptnt.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单取消时增加订单赠品的可用库存
 * @author Snow create in 2018/5/21
 * @version v2.0
 * @since v7.0.0
 */
@Component
public class OrderGiftStoreConsumer implements OrderStatusChangeEvent{

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private FullDiscountGiftClient fullDiscountGiftClient;

    @Autowired
    private OrderMetaClient orderMetaClient;

    @Override
    public void orderChange(OrderStatusChangeMsg orderMessage) {

        //已确认状态进行赠品入库 并 减少赠品可用库存
        if(orderMessage.getNewStatus().name().equals(OrderStatusEnum.CONFIRM.name())){
            //赠品入库
            addGift(orderMessage.getOrderDTO());
            //扣减赠品库存
            List<FullDiscountGiftDO> giftDOList = this.getList(orderMessage);
            logger.debug("扣减赠品可用库存,赠品数量：{}", giftDOList.size());
            this.fullDiscountGiftClient.reduceGiftQuantity(giftDOList, QuantityType.enable);
        }

        // 发货减少赠品真实库存
        if (orderMessage.getNewStatus().name().equals(OrderStatusEnum.SHIPPED.name())) {

            List<FullDiscountGiftDO> giftDOList = this.getList(orderMessage);
            logger.debug("扣减赠品实际库存,赠品数量：{}", giftDOList.size());
            this.fullDiscountGiftClient.reduceGiftQuantity(giftDOList, QuantityType.actual);
        }

        //取消状态增加赠品可用库存
        if(orderMessage.getNewStatus().name().equals(OrderStatusEnum.CANCELLED.name())){

            List<FullDiscountGiftDO> giftDOList = this.getList(orderMessage);
            this.fullDiscountGiftClient.addGiftEnableQuantity(giftDOList);
        }

    }

    /**
     * 查询赠品信息
     * @param orderMessage
     * @return
     */
    private List<FullDiscountGiftDO> getList(OrderStatusChangeMsg orderMessage){

        String fullDiscountGiftJson = this.orderMetaClient.getMetaValue(orderMessage.getOrderDO().getSn(), OrderMetaKeyEnum.GIFT);
        if(StringUtil.isEmpty(fullDiscountGiftJson)){
            return new ArrayList<>();
        }
        List<FullDiscountGiftDO> giftDOList = JsonUtil.jsonToList(fullDiscountGiftJson, FullDiscountGiftDO.class);

        return giftDOList;
    }

    /***
     * 赠品入库
     * @param orderDTO
     */
    private void addGift(OrderDTO orderDTO) {

        try {
            if(StringUtil.isEmpty(orderDTO.getGiftJson())){
                return;
            }

            //赠品入库
            List<GiveGiftVO> giftList= JsonUtil.jsonToList(orderDTO.getGiftJson(), GiveGiftVO.class);
            List<FullDiscountGiftDO> giftLists = new ArrayList<>();
            for (GiveGiftVO giveGiftVO:giftList) {
                if("gift".equals(giveGiftVO.getType())){
                    FullDiscountGiftDO fullDiscountGiftDO = fullDiscountGiftClient.getModel(Long.valueOf(giveGiftVO.getValue().toString()));
                    //赠品库存大于0，赠送赠品
                    if(fullDiscountGiftDO != null && fullDiscountGiftDO.getEnableStore() > 0){
                        giftLists.add(fullDiscountGiftDO);
                    }

                }
            }
            if(giftLists.size() > 0){
                OrderMetaDO giftMeta = new OrderMetaDO();
                giftMeta.setMetaKey(OrderMetaKeyEnum.GIFT.name());
                giftMeta.setMetaValue(JsonUtil.objectToJson(giftLists));
                giftMeta.setOrderSn(orderDTO.getSn());
                giftMeta.setStatus(OrderServiceStatusEnum.NOT_APPLY.name());
                this.orderMetaClient.add(giftMeta);
            }

            logger.debug("赠品入库完成");

        } catch (Exception e) {
            logger.error("赠品入库出错", e);
        }


    }
}
